<template>
  <div class="expand-container" ref="container">
    <div 
      class="text-content" 
      ref="textContent"
      :style="{ 
        'white-space': isExpanded ? 'normal' : 'nowrap',
        'text-overflow': isExpanded ? 'clip' : 'ellipsis'
      }"
    >
      {{ text }}
    </div>
    <span 
      v-if="showToggle || isExpanded" 
      class="toggle-btn" 
      @click="toggleExpand"
    >
      {{ isExpanded ? '收起' : '展开' }}
    </span>
  </div>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isExpanded: false,
      showToggle: false
    }
  },
  mounted() {
    this.checkOverflow();
    // 监听窗口变化重新计算
    window.addEventListener('resize', this.checkOverflow);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.checkOverflow);
  },
  methods: {
    checkOverflow() {
      this.$nextTick(() => {
        const container = this.$refs.container;
        const content = this.$refs.textContent;
        
        if (container && content) {
          // 比较内容宽度和容器宽度
          const contentWidth = content.scrollWidth;
          const containerWidth = container.offsetWidth;
          
          // 只有在未展开状态下才更新showToggle
          if (!this.isExpanded) {
            this.showToggle = contentWidth > containerWidth;
          }
        }
      });
    },
    toggleExpand() {
      this.isExpanded = !this.isExpanded;
      // 展开状态下强制显示按钮
      if (this.isExpanded) {
        this.showToggle = true;
      } else {
        // 收起后重新检查是否需要显示展开按钮
        this.$nextTick(this.checkOverflow);
      }
    }
  },
  watch: {
    text() {
      this.checkOverflow();
    }
  }
}
</script>

<style scoped>
.expand-container {
  display: flex;
  align-items: center;
  width: 100%; /* 或者指定宽度 */
  overflow: hidden;
}

.text-content {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  flex: 1;
}

.toggle-btn {
  color: #1890ff;
  height:20px;
  line-height:18px;
  cursor: pointer;
  padding:0 10px;
  border-radius:100px;
  color:rgb(41, 92, 255);
  text-decoration: none;
  font-size:14px;
}
</style>